package de.doegel.common;

import greendroid.widget.ActionBarItem;
import greendroid.widget.ActionBarItem.Type;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.LightingColorFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import de.doegel.common.ormlite.OrmLiteGDActivity;
import de.doegel.common.util.AbstractHttpConnector.SendMessageResponse;
import de.doegel.common.util.Util;
import de.doegel.common.util.Utils;

public class MessageComposeActivity<H extends AbstractDatabaseHelper> extends OrmLiteGDActivity<H>
{

	private class MessageStructure
	{
		public String	subject;
		public String	content;
		public int		personId;
	}

	private int		personId	= -1;
	private String	personName	= "";

	public Button	contactNameButton;
	public EditText	subjectEditText;
	public EditText	contentEditText;

	@Override
	public void onCreate( Bundle savedInstanceState )
	{
		super.onCreate(savedInstanceState);
		setActionBarContentView(R.layout.message_compose);
		setTitle(R.string.message_compose_activity_title);

		addActionBarItem(Type.Mail, R.id.action_bar_send);

		String subject = "";
		String content = "";
		Bundle extras = getIntent().getExtras();
		if (extras != null)
		{
			personId = extras.getInt(IDoegelConstants.PERSON_ID_EXTRA);
			personName = extras.getString(IDoegelConstants.PERSON_NAME_EXTRA);
			subject = extras.getString(IDoegelConstants.MESSAGE_SUBJECT_EXTRA);
			content = extras.getString(IDoegelConstants.MESSAGE_CONTENT_EXTRA);
		}

		contactNameButton = (Button) findViewById(R.id.contact_name);
		contactNameButton.setOnClickListener(new OnClickListener()
		{
			public void onClick( View v )
			{
				if (personId > 0)
				{
					startActivity(Utils.createPersonIntent(MessageComposeActivity.this, personId, personName));
				}
			}
		});
		contactNameButton.setEnabled(false);
		ImageButton addContactButton = (ImageButton) findViewById(R.id.pick_contact);
		addContactButton.setOnClickListener(new OnClickListener()
		{
			public void onClick( View v )
			{
				pickContact();
			}
		});
		// FIXME: convert white icon to black icon
		addContactButton.getDrawable().setColorFilter(new LightingColorFilter(Color.BLACK, Color.BLACK));
		subjectEditText = (EditText) findViewById(R.id.message_subject);
		contentEditText = (EditText) findViewById(R.id.message_content);

		contactNameButton.setText(personName);
		subjectEditText.setText(subject);
		contentEditText.setText(content);

		if (personId <= 0)
		{
			contactNameButton.setVisibility(View.INVISIBLE);
		}
	}

	@Override
	public boolean onHandleActionBarItemClick( ActionBarItem item , int position )
	{
		if (item.getItemId() == R.id.action_bar_send)
		{
			sendMessage();
			return true;
		}
		else
		{
			return super.onHandleActionBarItemClick(item, position);
		}
	}

	@Override
	public void onActivityResult( int requestCode , int resultCode , Intent data )
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK)
		{
			personId = data.getExtras().getInt(IDoegelConstants.PERSON_ID_EXTRA);
			personName = data.getExtras().getString(IDoegelConstants.PERSON_NAME_EXTRA);
			contactNameButton.setText(personName);
			if (personId > 0)
			{
				contactNameButton.setVisibility(View.VISIBLE);
			}
			else
			{
				contactNameButton.setVisibility(View.INVISIBLE);
			}
		}
	}

	public void pickContact()
	{
		Intent intent = Utils.createContactSearchIntent(this);
		intent.putExtra(IDoegelConstants.PICK_CONTACT_EXTRA, true);
		startActivityForResult(intent, 1);
	}

	@SuppressWarnings("unchecked")
	public void sendMessage()
	{
		MessageStructure obj = new MessageStructure();
		obj.subject = subjectEditText.getText().toString();
		obj.content = Util.ConvertToUT8(contentEditText.getText().toString());
		obj.personId = personId;
		if (obj.personId <= 0)
		{
			Utils.showAlertDialog(this, getString(R.string.dialog_warning), getString(R.string.message_empty_receiver));
			return;
		}
		if (TextUtils.isEmpty(obj.subject))
		{
			Utils.showAlertDialog(this, getString(R.string.dialog_warning), getString(R.string.message_empty_subject));
			return;
		}
		if (TextUtils.isEmpty(obj.content))
		{
			Utils.showAlertDialog(this, getString(R.string.dialog_warning), getString(R.string.message_empty_content));
			return;
		}

		new SendMessageTask().execute(obj);
	}

	private class SendMessageTask extends AsyncTask<MessageStructure, Void, SendMessageResponse>
	{
		ProgressDialog	dialog;

		@Override
		protected void onPreExecute()
		{
			dialog = new ProgressDialog(MessageComposeActivity.this);
			dialog.setMessage(getString(R.string.message_sending));
			dialog.setIndeterminate(true);
			dialog.setCancelable(false);
			dialog.show();
		}

		@Override
		protected SendMessageResponse doInBackground( MessageStructure... params )
		{
			MessageStructure obj = params[0];
			Log.d("message:", obj.content);
			return ((DoegelApplication) getApplication()).getHttpConnector().sendMessage(MessageComposeActivity.this, obj.personId, obj.subject, Util.ConvertToUT8(obj.content));
		}

		@Override
		protected void onPostExecute( SendMessageResponse result )
		{
			dialog.dismiss();
			if (result == SendMessageResponse.SUCCESSFUL)
			{
				finish();
			}
			else
			{
				String title = getString(R.string.message_sending_error_title);
				String content = getString(R.string.network_problem);
				if (result == SendMessageResponse.ERROR_NOT_PREMIUM_MEMBER)
				{
					content = getString(R.string.message_sending_error_not_premium_member);
				}
				else if (result == SendMessageResponse.ERROR_INVALID_ACCOUNT)
				{
					content = getString(R.string.message_sending_error_invalid_account);
				}
				Utils.showAlertDialog(MessageComposeActivity.this, title, content);
			}
			super.onPostExecute(result);
		}
	}

	private static final int	CONTEXT_MENU_HOME	= 0;
	private static final int	CONTEXT_MENU_PICK	= 1;
	private static final int	CONTEXT_MENU_SEND	= 2;

	@Override
	public boolean onCreateOptionsMenu( Menu menu )
	{
		menu.add(0, CONTEXT_MENU_HOME, 0, R.string.home_context_menu);
		menu.add(0, CONTEXT_MENU_PICK, 0, R.string.pick_contact_context_menu);
		menu.add(0, CONTEXT_MENU_SEND, 0, R.string.send_message_context_menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu( Menu menu )
	{
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected( MenuItem item )
	{
		switch (item.getItemId())
		{
			case CONTEXT_MENU_HOME:
				startActivity(Utils.createHomeIntent(this));
				return true;
			case CONTEXT_MENU_PICK:
				pickContact();
				return true;
			case CONTEXT_MENU_SEND:
				sendMessage();
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}
}
